﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoDbObject;
using System.Xml;
using SZJT.Utility.DataSource;

namespace Colligate.DataSource.DriverTraining.Business.Coach
{
    class DataNode_BusinessCoachInfo : BaseDataTree
    {
        private const string DATATYPE_COACH_INFO = "BizCoachInfo";
        private const string DATATYPE_COACH_QUERY = "BizCoachInfoQuery";
        private const string DATATYPE_COACH_CHGPWD = "BizCoachInfoChangePwd";
        //private Business_Coach _dataDefine;

        public DataNode_BusinessCoachInfo(string taskGuid, IDataSourceLayer dataLayer, IDataService dataService)
            : base(taskGuid, dataLayer, dataService)
        {
            _dataTypeList[DataTypeCategory.SET_DATA_LIST] = new string[] { DATATYPE_COACH_INFO };
            _dataTypeList[DataTypeCategory.GET_DATA_LIST] = new string[] { DATATYPE_COACH_INFO };
            _dataTypeList[DataTypeCategory.TRANSFORM_LIST] = new string[] { DATATYPE_COACH_QUERY };
            _dataDefine = new BusinessCoachInfo(dataLayer);
        }

        #region GetData
        public override XmlNode GetData(OUDataInfo UserInfo, string DataGuid, string DataType)
        {
            XmlNode ResultInfo = null;
            switch (DataType)
            {
                case DATATYPE_COACH_INFO:
                    ResultInfo = GetCoachInfo(UserInfo, DataGuid);
                    break;
            }
            return ResultInfo;
        }
        #endregion

        #region SetData
        public override int SetData(OUDataInfo UserInfo, string DataGuid, string DataType, System.Xml.XmlNode XmlData)
        {
            int nResult = 1001;
            switch (DataType)
            {
                case DATATYPE_COACH_INFO:
                    nResult = SetCoachInfo(UserInfo, DataGuid, XmlData);
                    break;
                case DATATYPE_COACH_CHGPWD:
                    nResult = ChangeCoachPassword(UserInfo, DataGuid, XmlData);
                    break;
            }
            return nResult;
        }

        protected int ChangeCoachPassword(OUDataInfo userInfo, string CoachGuid, XmlNode xmlData)
        {
            IDBDataObject InfoData = (_dataDefine as BusinessCoachInfo).GetCoachInfoData(CoachGuid);
            int result = -1;

            if (InfoData.ID == 0)
            {
                //No record found.
                result = -100;
            }
            else
            {
                string oldpassword = XmlNodeManage.GetSubValue(xmlData, "OldPassword");
                string newPassword = XmlNodeManage.GetSubValue(xmlData, "NewPassword");
                string databasePwd = InfoData["fCoachPassword"].ToString();

                if (string.Compare(databasePwd, oldpassword, false) != 0)
                {
                    //Original Password is not matching.
                    result = -101;
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(newPassword))
                    {
                        //New password is empty.
                        result = -102;
                    }
                    else
                    {
                        InfoData["fCoachPassword"] = newPassword;
                        result = InfoData.SaveData() ? 0 : 1;
                    }
                }
            }

            return result;
        }
        #endregion

        #region DeleteData

        public override int DeleteData(OUDataInfo UserInfo, string DataGuid, string DataType)
        {
            IDBDataObject InfoData = (_dataDefine as BusinessCoachInfo).GetCoachInfoData(DataGuid);

            string SenderGuid = InfoData["fSenderGuid"] as string;

            int nResult = 0;
            nResult = InfoData.DeleteData() ? 0 : 1;

            return nResult;
        }

        #endregion
        #region TransformData
        public override XmlNode TransformData(OUDataInfo UserInfo, string DataType, XmlNode XmlParam)
        {
            XmlNode ResultInfo = null;
            switch (DataType)
            {
                case DATATYPE_COACH_QUERY:
                    ResultInfo = GetCoachList(UserInfo, XmlParam);
                    break;
            }

            return ResultInfo;
        }
        #endregion

        #region 教练信息

        //<Document TaskGuid="{智慧驾培学事管理系统任务标识}" DataGuid="{教练基本信息标识}" DataType="BizCoachInfo">
        //    <CoachGuid Type="GUID" Mandatory="是">{教练基本信息标识}</CoachGuid>
        //    <CoachName Type="TEXT" Mandatory="是" Length="10">{教练姓名}</CoachName>
        //    <CoachAge Type="LONG" Mandatory="否" Length="2">{教练年龄}</CoachAge>
        //    <CoachSex Type="TEXT" Mandatory="是" Length="1">{教练性别[F:女性|M:男性]}</CoachSex>
        //    <CoachStatus Type="TEXT" Mandatory="是" Length="10">{教练状态[在岗|离职|停职]}</CoachStatus>
        //</Document>
        protected int SetCoachInfo(OUDataInfo UserInfo, string CoachGuid, XmlNode XmlData)
        {
            //if (!CheckPrivilege(UserInfo, "操作成员"))
            //    return -3;

            IDBDataObject InfoData = (_dataDefine as BusinessCoachInfo).GetCoachInfoData(CoachGuid);

            bool isNewCoach = (InfoData["ID"].ToString() == "0");

            string coachID = XmlNodeManage.GetSubValue(XmlData, "CoachID");
            string coachPassword = coachID.Length >= 6 ? coachID.Substring(coachID.Length - 6, 6) : coachID;
            XmlNodeManage.SetSubValue(XmlData, "CoachPassword", "TEXT", coachPassword);

            int nResult = 0;

            InfoData["fCoachGuid"] = XmlNodeManage.GetSubValue(XmlData, "CoachGuid");
            InfoData["fCoachCode"] = XmlNodeManage.GetSubValue(XmlData, "CoachCode");
            InfoData["fCoachName"] = XmlNodeManage.GetSubValue(XmlData, "CoachName");
            InfoData["fCoachID"] = XmlNodeManage.GetSubValue(XmlData, "CoachID");
            InfoData["fCoachAge"] = XmlNodeManage.GetSubValue(XmlData, "CoachAge");
            InfoData["fCoachSex"] = XmlNodeManage.GetSubValue(XmlData, "CoachSex");
            InfoData["fCoachMobile"] = XmlNodeManage.GetSubValue(XmlData, "CoachMobile");
            InfoData["fCoachStatus"] = XmlNodeManage.GetSubValue(XmlData, "CoachStatus");
            InfoData["fSchoolGuid"] = XmlNodeManage.GetSubValue(XmlData, "SchoolGuid");
            InfoData["fSchoolName"] = XmlNodeManage.GetSubValue(XmlData, "SchoolName");
            InfoData["fCoachAccount"] = XmlNodeManage.GetSubValue(XmlData, "CoachAccount");
            InfoData["fCoachMail"] = XmlNodeManage.GetSubValue(XmlData, "CoachMail");

            if (isNewCoach)
            {
                InfoData["fCoachPassword"] = coachPassword;
            }

            nResult = InfoData.SaveData() ? 0 : 4;

            if (isNewCoach)
            {
                XmlNodeManage.SetSubValue(XmlData, "StudentPassword", "TEXT", coachPassword);
                nResult = nResult | CreateCoachLoginAccount(UserInfo, CoachGuid, XmlData); ;
            }

            return nResult;
        }

        /// <summary>
        /// 基于教练的GUID取得教练的信息
        /// </summary>
        protected XmlNode GetCoachInfo(OUDataInfo UserInfo, string CoachGuid)
        {
            //if (!CheckPrivilege(UserInfo, "操作成员"))
            //    return null;

            IDBDataObject InfoData = (_dataDefine as BusinessCoachInfo).GetCoachInfoData(CoachGuid);
            //string SenderGuid = NotesInfoData["fSenderGuid"] as string;
            XmlNode xmlNotesInfoData = XmlNodeManage.GetDocumentNode(_taskGuid, CoachGuid, DATATYPE_COACH_INFO);

            XmlNodeManage.SetSubValue(xmlNotesInfoData, "CoachGuid", "GUID", InfoData["fCoachGuid"]);
            XmlNodeManage.SetSubValue(xmlNotesInfoData, "CoachCode", "TEXT", InfoData["fCoachCode"]);
            XmlNodeManage.SetSubValue(xmlNotesInfoData, "CoachName", "TEXT", InfoData["fCoachName"]);
            XmlNodeManage.SetSubValue(xmlNotesInfoData, "CoachID", "TEXT", InfoData["fCoachID"]);
            XmlNodeManage.SetSubValue(xmlNotesInfoData, "CoachAge", "LONG", InfoData["fCoachAge"]);
            XmlNodeManage.SetSubValue(xmlNotesInfoData, "CoachSex", "TEXT", InfoData["fCoachSex"]);
            XmlNodeManage.SetSubValue(xmlNotesInfoData, "CoachMobile", "TEXT", InfoData["fCoachMobile"]);
            XmlNodeManage.SetSubValue(xmlNotesInfoData, "CoachStatus", "TEXT", InfoData["fCoachStatus"]);
            XmlNodeManage.SetSubValue(xmlNotesInfoData, "SchoolGuid", "GUID", InfoData["fSchoolGuid"]);
            XmlNodeManage.SetSubValue(xmlNotesInfoData, "SchoolName", "TEXT", InfoData["fSchoolName"]);
            XmlNodeManage.SetSubValue(xmlNotesInfoData, "CoachAccount", "TEXT", InfoData["fCoachAccount"]);
            XmlNodeManage.SetSubValue(xmlNotesInfoData, "CoachMail", "TEXT", InfoData["fCoachMail"]);

            return xmlNotesInfoData;
        }

        ///<summary>
        ///模块分类：驾校运营 Coach
        ///功能分类：教练管理 Coach
        ///分类序号：1002 Coach
        ///数据编号：ZHJP-BUSINESS-COACH-1002 Coach
        ///数据名称：教练基本信息查询 Coach
        ///数据代码：BizCoachInfoQuery Coach
        ///数据说明：教练员的基本信息查询 Coach
        /// </summary>
        /// 
        ///---------------- 查询条件 数据规范---------------------
        /// <Document TaskGuid="{智慧驾培学事管理系统任务标识}" DataGuid="{教练基本信息查询标识}" DataType="BizCoachInfoQuery">
        ///    <PageIndex Type="LONG" Mandatory="是" Length="8">{查询页码}</PageIndex>
        ///    <PageSize Type="LONG" Mandatory="是" Length="8">{查询页面大小}</PageSize>
        ///    <CoachName Type="TEXT" Mandatory="否" Length="10">{教练姓名}</CoachName>
        ///    <CoachAgeStart Type="LONG" Mandatory="否" Length="2">{年龄开始值}</CoachAgeStart>
        ///    <CoachAgeEnd Type="LONG" Mandatory="否" Length="2">{年龄结束值}</CoachAgeEnd>
        ///    <CoachSex Type="TEXT" Mandatory="否" Length="1">{教练性别[F:女性|M:男性]}</CoachSex>
        ///    <CoachStatus Type="TEXT" Mandatory="否" Length="10">{教练状态[在岗|离职|停职]}</CoachStatus>
        ///</Document>
        /// 
        ///---------------- 查询返回 数据规范---------------------
        ///<Document TaskGuid="{智慧驾培学事管理系统任务标识}" DataGuid="{教练基本信息查询标识}" DataType="BizCoachInfoQuery">
        ///    <RecordCount Type="LONG" Mandatory="是" Length="8">{查询结果总记录数}</RecordCount>
        ///    <PageSize Type="LONG" Mandatory="是" Length="8">{实际返回页面大小}</PageSize>
        ///    <PageIndex Type="LONG" Mandatory="是" Length="8">{实际返回页码}</PageIndex>
        ///    <CoachList>
        ///        <CoachInfo>
        ///            <CoachGuid Type="GUID" Mandatory="是" Length="36">{教练标识}</CoachGuid>
        ///            <CoachName Type="TEXT" Mandatory="是" Length="10">{教练姓名}</CoachName>
        ///            <CoachAge Type="LONG" Mandatory="否" Length="2">{教练年龄}</CoachAge>
        ///            <CoachSex Type="TEXT" Mandatory="是" Length="1">{教练性别[F:女性|M:男性]}</CoachSex>
        ///            <CoachStatus Type="TEXT" Mandatory="是" Length="10">{教练状态[在岗|离职|停职]}</CoachStatus>
        ///        </CoachInfo>
        ///        <!-- 重复CoachInfo -->
        ///    </CoachList>
        ///</Document>
        protected XmlNode GetCoachList(OUDataInfo UserInfo, XmlNode XmlParam)
        {
            string queryName = XmlNodeManage.GetSubValue(XmlParam, "CoachName");
            string queryCoachCode = XmlNodeManage.GetSubValue(XmlParam, "CoachCode");
            string queryCoachAgeStart = XmlNodeManage.GetSubValue(XmlParam, "CoachAgeStart");
            string queryCoachAgeEnd = XmlNodeManage.GetSubValue(XmlParam, "CoachAgeEnd");
            string queryCoachSex = XmlNodeManage.GetSubValue(XmlParam, "CoachSex");
            string queryCoachStatus = XmlNodeManage.GetSubValue(XmlParam, "CoachStatus");
            string querySchoolGuid = XmlNodeManage.GetSubValue(XmlParam, "SchoolGuid");
            string queryPageIndex = XmlNodeManage.GetSubValue(XmlParam, "PageIndex");
            string queryPageSize = XmlNodeManage.GetSubValue(XmlParam, "PageSize");


            //Generate query string,
            QueryFilter strQueryFilter = new QueryFilter();

            strQueryFilter.AddFilter("fCoachName", QueryFilter.FilterType.TEXT, queryName);
            strQueryFilter.AddFilter("fCoachCode", QueryFilter.FilterType.TEXT, queryCoachCode);
            strQueryFilter.AddFilter("fCoachAge", queryCoachAgeStart, "{0} > {1}");
            strQueryFilter.AddFilter("fCoachAge", queryCoachAgeEnd, "{0} < {1}");
            strQueryFilter.AddFilter("fCoachSex", QueryFilter.FilterType.TEXT, queryCoachSex);
            strQueryFilter.AddFilter("fCoachStatus", QueryFilter.FilterType.TEXT, queryCoachStatus);
            strQueryFilter.AddFilter("fSchoolGuid", QueryFilter.FilterType.TEXT, querySchoolGuid);

            IDBBigObjectSet coachList = (_dataDefine as BusinessCoachInfo).GetCoachListByFilter(strQueryFilter.FilterString);

            //For paging
            List<IDBDataObject> resultList = GetPageDataSet(coachList, ref queryPageIndex, ref queryPageSize);

            XmlNode xmlQueryData = XmlNodeManage.GetDocumentNode(_taskGuid, "", DATATYPE_COACH_QUERY);
            //Add the paging nodes.
            XmlNodeManage.SetSubValue(xmlQueryData, "RecordCount", "LONG", coachList.DataCount);
            XmlNodeManage.SetSubValue(xmlQueryData, "PageSize", "LONG", queryPageSize);
            XmlNodeManage.SetSubValue(xmlQueryData, "PageIndex", "LONG", queryPageIndex);

            XmlNode coachRoot = XmlNodeManage.CreateNode("CoachList");
            XmlNode subNode;

            foreach (IDBDataObject coachInfo in resultList)
            {
                subNode = XmlNodeManage.CreateNode("CoachInfo");

                XmlNodeManage.SetSubValue(subNode, "CoachGuid", "GUID", coachInfo["fCoachGuid"]);
                XmlNodeManage.SetSubValue(subNode, "CoachCode", "TEXT", coachInfo["fCoachCode"]);
                XmlNodeManage.SetSubValue(subNode, "CoachName", "TEXT", coachInfo["fCoachName"]);
                XmlNodeManage.SetSubValue(subNode, "CoachID", "TEXT", coachInfo["fCoachID"]);
                XmlNodeManage.SetSubValue(subNode, "CoachAge", "LONG", coachInfo["fCoachAge"]);
                XmlNodeManage.SetSubValue(subNode, "CoachSex", "TEXT", coachInfo["fCoachSex"]);
                XmlNodeManage.SetSubValue(subNode, "CoachMobile", "TEXT", coachInfo["fCoachMobile"]);
                XmlNodeManage.SetSubValue(subNode, "CoachStatus", "TEXT", coachInfo["fCoachStatus"]);
                XmlNodeManage.SetSubValue(subNode, "SchoolGuid", "GUID", coachInfo["fSchoolGuid"]);
                XmlNodeManage.SetSubValue(subNode, "SchoolName", "TEXT", coachInfo["fSchoolName"]);
                XmlNodeManage.SetSubValue(subNode, "CoachAccount", "TEXT", coachInfo["fCoachAccount"]);
                XmlNodeManage.SetSubValue(subNode, "CoachMail", "TEXT", coachInfo["fCoachMail"]);

                coachRoot.AppendChild(subNode);
            }
            xmlQueryData.AppendChild(coachRoot);
            return xmlQueryData;
        }


        //<Document TaskGuid = "组件标识" DataGuid = "人员标识" DataType = "Member">
        //    <Guid Type = "GUID">人员标识</Guid>
        //    <Name Type = "TEXT">姓名</Name>
        //    <BranchGuid Type = "GUID">部门标识</BranchGuid>
        //    <BranchName Type = "GUID">部门名称</BranchName>
        //    <Telephone Type = "TEXT">联系电话</Telephone>
        //    <Handphone1 Type = "TEXT">移动电话1</Handphone1>
        //    <Handphone2 Type = "TEXT">移动电话2</Handphone2>
        //    <EMail Type = "TEXT">邮箱</EMail>
        //    <Order Type = "LONG">序号</Order>
        //</Document>
        //<Document TaskGuid = "组件标识" DataGuid = "账户标识" DataType = "Account">
        //    <Guid Type = "GUID">组织单元标识</Guid>
        //    <AccountName Type = "TEXT">账户名</AccountName>
        //    <Password Type = "TEXT">密码</Password>
        //    <Type Type = "TEXT">账户类型[Member|Platform]</Type>
        //    <Name Type = "TEXT">组织单元名称</Name>
        //    <IsEvection Type= "LOGICAL">是否外出【true：外出|false：在岗】</IsEvection>
        //    <Status Type = "LOGICAL">账户状态【true：启用|false：禁用】</Status>
        //</Document>
        protected int CreateCoachLoginAccount(OUDataInfo userInfo, string CoachGuid, XmlNode xmlData)
        {
            string taskGuidOrg = "0690f841-7773-445c-9f48-a7a0427686d5";

            XmlNode xmlMemberData = XmlNodeManage.GetDocumentNode(taskGuidOrg, CoachGuid, "Member");
            XmlNodeManage.SetSubValue(xmlMemberData, "Guid", "GUID", XmlNodeManage.GetSubValue(xmlData, "CoachGuid"));
            XmlNodeManage.SetSubValue(xmlMemberData, "Name", "TEXT", XmlNodeManage.GetSubValue(xmlData, "CoachName"));
            XmlNodeManage.SetSubValue(xmlMemberData, "BranchGuid", "TEXT", "G_Coach");
            XmlNodeManage.SetSubValue(xmlMemberData, "BranchName", "TEXT", "学员");
            XmlNodeManage.SetSubValue(xmlMemberData, "Telephone", "TEXT", XmlNodeManage.GetSubValue(xmlData, "CoachMobile"));
            XmlNodeManage.SetSubValue(xmlMemberData, "EMail", "LOGICAL", XmlNodeManage.GetSubValue(xmlData, "CoachMail"));
            XmlNodeManage.SetSubValue(xmlMemberData, "Order", "LONG", "1");

            int result = (_dataService.SetTaskData(taskGuidOrg, CoachGuid, "Member", xmlMemberData) == 0 ? 0 : 2);

            XmlNode xmlAccountData = XmlNodeManage.GetDocumentNode(taskGuidOrg, CoachGuid, "Account");
            XmlNodeManage.SetSubValue(xmlAccountData, "Guid", "GUID", XmlNodeManage.GetSubValue(xmlData, "CoachGuid"));
            XmlNodeManage.SetSubValue(xmlAccountData, "AccountName", "TEXT", XmlNodeManage.GetSubValue(xmlData, "CoachAccount"));
            XmlNodeManage.SetSubValue(xmlAccountData, "Password", "TEXT", XmlNodeManage.GetSubValue(xmlData, "CoachPassword"));
            XmlNodeManage.SetSubValue(xmlAccountData, "Type", "TEXT", "User");
            XmlNodeManage.SetSubValue(xmlAccountData, "Name", "TEXT", "Coach");
            XmlNodeManage.SetSubValue(xmlAccountData, "IsEvection", "LOGICAL", "false");
            XmlNodeManage.SetSubValue(xmlAccountData, "Status", "LOGICAL", "true");

            result += (_dataService.SetTaskData(taskGuidOrg, CoachGuid, "Account", xmlAccountData) == 0 ? 0 : 1);
            return result;
        }

        #endregion

        #region Paging
        /// <summary>
        /// 
        /// </summary>
        /// <param name="allRecords"></param>
        /// <param name="queryPageIndex"></param>
        /// <param name="queryPageSize"></param>
        /// <returns></returns>
        private List<IDBDataObject> GetPageDataSet(IDBBigObjectSet allRecords, ref string queryPageIndex, ref string queryPageSize)
        {
            List<IDBDataObject> currentPageRecord = new List<IDBDataObject>();
            const int DEFAULT_PAGESIZE = 10;
            const int DEFAULT_PAGEINDEX = 0;

            int pageSize = 0;
            int pageIndex = 0;
            int currentRow = 0;
            int fromIndex = 0;

            if (allRecords.DataCount > 0)
            {
                #region Paging Index verificaiton.

                //if the invalid paging data, then set to be default value.
                if (!int.TryParse(queryPageSize, out pageSize))
                {
                    pageSize = DEFAULT_PAGESIZE;
                }

                if (!int.TryParse(queryPageIndex, out pageIndex))
                {
                    pageIndex = DEFAULT_PAGEINDEX;
                }

                pageSize = pageSize == 0 ? DEFAULT_PAGESIZE : pageSize;
                fromIndex = pageIndex * pageSize;

                //if the total count is less than the from index, then get the last page.
                if (allRecords != null && allRecords.DataCount < fromIndex)
                {
                    int restCount = allRecords.DataCount % pageSize;

                    if (restCount == 0)
                    {
                        restCount = pageSize;
                    }

                    fromIndex = allRecords.DataCount - restCount;

                    pageIndex = fromIndex / pageSize;
                }

                //get back the value for the output
                queryPageIndex = pageIndex.ToString();
                queryPageSize = pageSize.ToString();

                #endregion

                #region Get Fields Data
                allRecords.MoveTo(fromIndex);
                while (currentRow < pageSize && fromIndex < allRecords.DataCount)
                {
                    //Get all the field values.
                    CDBDataObject obj = new CDBDataObject(allRecords.TableName, allRecords.DBSystem.FieldList, allRecords.DataSourceLayer);
                    string fieldName = string.Empty;

                    int fieldCount = allRecords.DBSystem.FieldCount;
                    for (int i = 0; i < fieldCount; i++)
                    {
                        fieldName = allRecords.DBSystem[i].ColumnName;
                        obj.SetObject(fieldName, allRecords[fieldName]);
                    }

                    currentPageRecord.Add(obj);

                    allRecords.MoveNext();
                    currentRow++;
                    fromIndex++;
                }
                #endregion
            }
            return currentPageRecord;
        }
        #endregion



    }
}